package ru.incoremedia.gwttest.core.client.component.autosizedtextarea;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TextArea;
import java.util.ArrayList;
import java.util.List;


public class AutoSizedTextArea extends TextArea implements HasTextChangeHandler {

    private HTML hiddenDiv;

    public List<TextChangeHandler> textChangeHandlers = new ArrayList<TextChangeHandler>();

    public AutoSizedTextArea() {
        setStyleName(AutoSizedTextAreaResourceBundle.INSTANCE.cssResources().textAreaStyle());
        
        addKeyUpHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent event) {
                DeferredCommand.addCommand(new Command() {
                    @Override
                    public void execute() {
                        correctLines();
                    }
                });
            }
        });

        addValueChangeHandler(new ValueChangeHandler<String>() {
            @Override
            public void onValueChange(ValueChangeEvent<String> event) {
                DeferredCommand.addCommand(new Command() {
                    @Override
                    public void execute() {
                        correctLines();
                    }
                });
            }
        });

        sinkEvents(Event.ONPASTE);
    }

    @Override
    public void onBrowserEvent(Event event) {
        final int eventType = event.getTypeInt();
        switch (eventType) {
            case Event.ONPASTE:
                DeferredCommand.addCommand(new Command() {
                    @Override
                    public void execute() {
                        correctLines();
                    }
                });
                break;
        }
        super.onBrowserEvent(event);
    }

    public void correctLines() {
        String text = getText();

        if(text.length() == 0)text = " ";

        if(text.substring(text.length() - 1).equals("\n")) {//ie8 fix
            text += " ";
        }

        hiddenDiv.setText(text);

        setHeight(hiddenDiv.getElement().getClientHeight() + "px");
        
        for(TextChangeHandler handler : textChangeHandlers) {
            handler.onChange();
        }
    }

    @Override
    public void addTextChangeHandler(TextChangeHandler handler) {
        textChangeHandlers.add(handler);
    }

    public void setHiddenDiv(HTML hiddenDiv) {
        this.hiddenDiv = hiddenDiv;        
    }

    public HTML getHiddenDiv() {
        return hiddenDiv;
    }
}
